<?php
	class CategoriesController
	{
        private $model;
        private $view;
        
        public function __construct($model, $view) {
            $this->model = $model;
            $this->view  = $view;
            $view->setController($this);
        }
		
        // Parse the actions
        public function parseActions() {
            // See if there are actions to be taken:
            if(isset($_POST['save'])) {
                // Save the option:
				$name        = makeSafe($_POST['name']);
				$description = makeSafe($_POST['description']);
				$id_datatype = makeSafe($_POST['id_datatype']);
				$id_category = makeSafe($_POST['id_category']);
				$action      = makeSafe($_POST['action']);				
                $values = array('name'=>$name, 'description'=>$description, 'id_datatype'=>$id_datatype, 'id_category'=>$id_category);
                if($action=='add') {
                    $this->model->addCategory($values);
                } elseif($action=='edit') {
                    $id = $_POST['id'];
                    $this->model->updateCategory($id, $values);
                }
            } elseif(isset($_POST['delete'])) {
                // Delete the option:
                $id = $_POST['id'];
                $this->model->deleteCategory($id);
            }
        }
        
        // Render the view
        public function render() {
            // Show the interface:
            $this->view->showTop();
            if(isset($_POST['add'])) {
                $values = array('name'=>'', 'description'=>'', 'id_datatype'=>0, 'id_category'=>0, 'action'=>'add');
                $this->view->showForm($values);
            } elseif (isset($_POST['edit'])) {
                $id               = $_POST['id'];
                $values           = $this->model->getCategory($id);
                $values['action'] = 'edit';
                $this->view->showForm($values);
            } else {                
                $records = $this->model->getRecords();
                if(count($records)==0) {
                    $this->view->showNoRecordsAvailable();    
                } else {
                    $this->view->showRecords($records);
                }
                $this->view->showAddEditDelete();
            }
            $this->view->showBottom();
        }
		
		// Return an array with the availabel datatypes
		public function getDataTypes() {
			return $this->model->getDataTypes();
		}
		
        // Return an array with available categories
        public function getCategories() {
            return $this->model->getRecords();
        }		
	}
?>